<?php

namespace backend\controllers;

use Yii;
use backend\models\PayTrade;
use backend\models\PayTradeSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\ForbiddenHttpException;
use liangzoe\mobilesmser\TextSmser;
use common\models\SmsLogRecord;
use common\models\UserInfo;
use backend\models\PayUserDiscount;
use backend\models\CustomTrade;
use backend\models\AdminInfo;
use liangzoe\payment\weixin;
use liangzoe\payment\offline;
use backend\models\LogPay;
use backend\models\Image;
use backend\models\UserCoupon;
use backend\models\SysUserDesigner;
use backend\models\OperatorRelation;
use yii\grid\GridView;
use backend\models\PayLogisticsSearch;
use yii\helpers\Html;
use yii\base\Object;

/**
 * PayTradeController implements the CRUD actions for PayTrade model.
 */
class PayTradeController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    public function beforeAction($action)
    {
        
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}  	  	
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can('pay-trade') || \Yii::$app->user->can('Report')){
    		$access = $this->_checkAccess($action);
    		if($access){
    			return $access;
    		}else{
    			throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    		}
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	} 
    }
    function _checkAccess($action){
    	$action_list = array(
    			'update',
    			'audit',
    	);
    	if(in_array($action, $action_list)){
    		$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : $_REQUEST['trade_id'];
    		$model = $this->findModel($id);
    		$login_id = Yii::$app->user->identity->id;
    	    if(AdminInfo::check_sale($model, $login_id,$action)){
    			return true;
    		}else{
    			return false;
    		}
    	}else{
    			return true;
    	}
    }
    /**
     * Lists all PayTrade models.
     * @return mixed
     */
    public function actionIndex()
    {
        
       
        $searchModel = new PayTradeSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        
        //test
        //test
        
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * 支付明细
     */
    public function actionLogpay(){
        $searchModel = new PayTradeSearch();
        $dataProvider = $searchModel->logpaysearch(Yii::$app->request->queryParams);
        return $this->render('logpay_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * 众筹的订单管理
     */
    public function actionCrowdindex(){
        $searchModel = new PayTradeSearch();
        $dataProvider = $searchModel->crowd_search(Yii::$app->request->queryParams);
        return $this->render('crowd_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    //待催客户款
    public function actionDunning()
    {
        $searchModel = new PayTradeSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,true);
        
        return $this->render('dunning_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    //待催款详情
    public function actionDunningDetail()
    {
        $searchModel = new PayLogisticsSearch();
        $searchModel->trade_id=Yii::$app->request->get('trade_id');
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,false,true);
	  echo GridView::widget([
        //'filterModel'=>$searchModel,
            'dataProvider'=>$dataProvider,
            'columns'=>[
                'id',
                'trade_id',
                'item_id',
                'iteminfo.name',
		 		'number',
		  		[	
                    'attribute'=>'send_time',
                    'contentOptions'=>['width'=>'90px'],
                    'value'=>function($model){
                        if ($model->send_time != 0){
                            return date('Y-m-d',$model->send_time);
                        }elseif(isset($model->iteminfo->supply_cycle) && isset($model->tradeinfo->logPayInfoFirst)){
                            return date('Y-m-d',$model->tradeinfo->logPayInfoFirst->starttime + intval($model->iteminfo->supply_cycle)*30*24*3600);
                        }elseif (isset($model->tradeinfo->logPayInfoFirst)){
                            return date('Y-m-d',$model->tradeinfo->logPayInfoFirst->starttime + 30*24*3600);
                        }
                    }
                ],
                [
                    'header'=>'预览',
                    'format'=>'Html',
                    'value'=>function($model){
                        if (isset($model->iteminfo->defaultSmallImage)){
                            return Html::img('@web/'.$model->iteminfo->defaultSmallImage->url,['height'=>'50px']);
                        }else{
                            return '';
                        }
                    }
                ]
            ]
        ]);
    }
    /**
     * Displays a single PayTrade model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        //test
        
 /*        $str="eyJpdGVtX2lkIjoyNTU5LCJ0eXBlIjoyLCJ1c2VyX2lkIjoyMDA5LCJzZXNzaW9uIjp7InNpZCI6IjM3NjcwMiIsInRva2VuIjoiOWMwOGE3Y2VlYWNmMzY3YjMwYTQ3MjA4YjhiZDkyYTA3NTE0MWMifX0=";
        $get_info=base64_decode($str);
        $get_info=json_decode($get_info);
        
        print_R($get_info); */
 
        //
 /*        $test=array("item_id" => 2874 ,"type" => 0, "user_id"=> 2009 ,"session" => array( "sid" => 376702, "token" => "9c08a7ceeacf367b30a47208b8bd92a075141c"));
        //
        $get_info=json_encode($test);
        $get_info=base64_encode($get_info);
        print_R($get_info);exit();
        //
        $str=base64_encode($str); */
        //test
    	$this->layout = 'main_small';
    	$model = $this->findModel($id);
        $model->originPrice = PayTrade::calculate($model->content)['originPrice'];
        $content=json_decode($model->content);
        $pos=intval(strpos($model->content, "totle"));
        if($pos>0){
           $totle=$content->totle;
          $sales_logistics=$totle[0]->info->sales_logistics;
           $sales_service=$totle[0]->info->sales_service;
           $sales_design=$totle[0]->info->sales_design;
           $model->price_freight=intval($sales_logistics);
           $model->installprice=intval($sales_service); 
           $model->designprice=intval($sales_design);  
           
        }else{
            $model->price_freight=0;
            $model->installprice=0;
            $model->designprice=0;
        }
        //根据用户类型判断物流类型 user_type  3 4 5 到付  
        $user_id=intval($model->user_id);
        $expense_str="";
        $userInfo=UserInfo::findOne($user_id);
        if($userInfo){
            $user_type=intval($userInfo->user_type);
            if($user_type==3||$user_type==4||$user_type==5){
                $expense_str="按实际金额到付";
            }else{
                $expense_str="江浙沪包配送安装，超出区域按实际支付";
            }
        }
        
            
        
        //物流安装费 设计费
    	return $this->render('view', [
    	    'model' => $model,'expense_str'=>$expense_str
        ]);
    }

    /**
     * Creates a new PayTrade model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    /*
    public function actionCreate()
    {
        $model = new PayTrade();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    */
    function _discount($user_type,$user_type_class,$discount,$login_id,$user_id){
    	$msg = '';
    	$error = true;
    	if($user_id>0 && $login_id>0){
    		$login_info = AdminInfo::findOne(['id'=>$login_id]);
    		if($login_info['username'] == 'admin' && $login_info['user_type'] == 1){
    			if( $discount < 0.4)
    				$msg = '注册用户不能低于0.4折';
    			else
    				$error = false;//可以正确改价   		    			
    		}elseif($login_info['user_type'] == 1){//后台管理员的改价操作
    		     
    			if( $discount < 0.5){
    				$msg = '注册用户不能低于0.5折';
    			}else {
    			    $error = false;//可以正确改价
    			}
    			   
    		}elseif($login_info['user_type'] > 1){//运营商的改价操作
    		    if(($user_type==1||$user_type==2) && $discount < 0.65){
    				$msg = '注册用户不能低于0.65折';
    			}elseif ($user_type == 3){
    				if($user_type_class==5){//付费审计师
    					if($discount < 0.5){
    						$msg = '付费认证VIP会员不能低于0.5折';
    					}else{
    						$error = false;
    					}				
    				}else if($user_type_class==1){//非付费VIP会员
    					if($discount < 0.5){
    						$msg = '一般VIP会员不能低于0.5折';
    					}else{
    						$error = false;
    					}					
    				}
    			}elseif($user_type == 4  && $discount < 0.5){
    				$msg = '装饰企业不能低于0.5折';
    			}else{
    				$error = false;//可以正确改价
    			}
    		}else{
    			$msg = '价格更改失败';
    		}
    	}else{
    		$msg = '价格更改失败';
    	}

    	return array('error'=>$error,'msg'=>$msg);
    }
    /**
     * 销售人员更新订单
     * Updates an existing PayTrade model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
	        $model = $this->findModel($id);
	        $model->originPrice = PayTrade::calculate($model->content)['originPrice'];
	        //
	        $content=json_decode($model->content);
	        $pos=intval(strpos($model->content, "totle"));
	        if($pos>0){
	            $totle=$content->totle;
	            $sales_logistics=$totle[0]->info->sales_logistics;
	            $sales_service=$totle[0]->info->sales_service;
	            $sales_design=$totle[0]->info->sales_design;
	            $model->price_freight=intval($sales_logistics);
	            $model->installprice=intval($sales_service);
	            $model->designprice=intval($sales_design);
	            
	        }else{
	            $model->price_freight=0;
	            $model->installprice=0;
	            $model->designprice=0;
	        }
	        
			$check_modify_auth = $this->modify_auth($model->user_id);
			$login_id = Yii::$app->user->identity->id;

	        if($model->user_id == $login_id){
	        	throw new ForbiddenHttpException('不能修改自己的订单');
	        }
	        if ($model->load(Yii::$app->request->post())) {

	        	$model_update = $this->findModel($id);
	        	$return = $this->get_item_ids($model->content);
	        	$origin_price = $return['price_base'] + $return['price_custom'];//原价
	        	
	        	$user_type = $model->userInfo->user_type;
	        	$user_type_class = $model->userInfo->user_type_class;
	        	if($origin_price > 0){
	        	    
		        	$discount = $model->price_modify/$origin_price;
		        	if(AdminInfo::check_sale($model_update, $login_id,'update')){//有权限
			        		$_dicount = $this->_discount($user_type, $user_type_class, $discount, $login_id,$model_update['user_id']);
			        		if($_dicount['error'] === true){
			        			$msg = $_dicount['msg'];
			        			echo '<script type="text/javascript">alert("'.$msg.'");</script>';
			        			return $this->render('update', [
			        					'model' => $model,
			        					'check_modify_auth'=>$check_modify_auth,
			        				]);
			        		}
		        	}else{
		        		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
		        	}
	        	}
	        	
	        	if ($model->price_modify != $model_update->price_modify){
    	        	/*修改了价格，没有改价原因*/
    	        	if($model->price_modify != $model_update->price_modify && $model->price_m_memo == $model_update->price_m_memo){
    	        		echo '<script type="text/javascript">alert("价格修改后请填写改价原因");</script>';
    	        		return $this->render('update', [
    		               'model' => $model,
    	        			'check_modify_auth'=>$check_modify_auth,
    		         	]);
    	        	}
    	        	
    	        	/*修改了价格，也有改价原因*/
    		        if($model->price_modify != $model_update->price_modify && $model->price_m_memo != $model_update->price_m_memo){
    		        		$model->modify_time = time();
    		        		$model->modify_uid = Yii::$app->user->identity->id;
    		        		$model->save();//判断是修改了价格和原因
    		        		$model_update->trade_state = 6;//订单状态改为6
    		        		$model_update->audit_state = 0;//审核状态为0，继续审核
    		        		$model_update->audit_uid = 0;
    		        		$model_update->audit_time = 0;
    		        		$model_update->save();
    		        		return $this->redirect(['view', 'id' => $model->id]);
    		        }
	        	}else{
	        	    $model->save();
	        	}
		        return $this->redirect(['view', 'id' => $model->id]);
	        }elseif(($model->trade_state ==0||$model->trade_state==6) && $model->audit_state ==0 && $model->price==$model->price_modify) {
		        return $this->render('update', [
		               'model' => $model,
		        	   'check_modify_auth'=>$check_modify_auth,
		         ]);
	        }elseif(($model->trade_state ==0||$model->trade_state==6)/* && $model->audit_state ==1*/ && $model->price!=$model->price_modify) {
	            return $this->render('update', [
	            			'model' => $model,
	            			'check_modify_auth'=>$check_modify_auth,
	            ]);
	     	}else{
	        	throw new ForbiddenHttpException(Yii::t('app','Sorry , This trade can not been updated'));
	        }

}
function _check_modify_price(){
	
}
/*运营商不能修改VIP会员和装饰公司订单的价格*/
function modify_auth($user_id){
	$user_info = UserInfo::findOne(['id'=>$user_id]);
	$user_type = $user_info->user_type;
	if(in_array($user_type, array('3','4')) && Yii::$app->user->identity->user_type != 1){
		return true;//取消此项限制
	}
	return true;
}
function get_item_ids($content){
	$ids=array();
	$price_bace=0;
	$price_custom = 0;
	foreach (json_decode($content,true) as $key => $value){
		if($key == 'singleItem'){
			foreach ($value as $vo){
				foreach ($vo['items'] as $voo){
					$count = array_key_exists('count',$voo) ? intval($voo['count']) : 1;
					if(array_key_exists('item_id',$voo))
						array_push($ids, $voo['item_id']);
					if(array_key_exists('price_base',$voo))
						$price_bace += $voo['price_base']*$count;
					if(array_key_exists('_price_custom',$voo))
						$price_custom += $voo['_price_custom']*$count;
				}
			}
		}
		if($key == 'tz'){
			foreach ($value as $vo){
				foreach ($vo['items'] as $voo){
					if(array_key_exists('item_id',$voo))
						array_push($ids, $voo['item_id']);
					if(array_key_exists('price_base',$voo))
						$price_bace +=$voo['price_base'];
					if(array_key_exists('_price_custom',$voo))
						$price_custom +=$voo['_price_custom'];
				}
			}
		}
	}
	$return['ids'] = $ids;
	$return['price_base'] = $price_bace;
	$return['price_custom'] = $price_custom;
	return $return;
}
    /**
     * 销售主管审核订单
     * Updates an existing PayTrade model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionAudit($id)
    {   	
    	$model = $this->findModel($id);
    	$login_id = Yii::$app->user->identity->id;
    	if($model->user_id == $login_id){
    		throw new ForbiddenHttpException('不能审核自己的订单');
    	}
    	if ($model->load(Yii::$app->request->post())) {
    			$model_audit = $this->findModel($id);//只更新审核的数据
    			if($model->audit_state == 1){
    			
    				$model_audit->audit_state = 1;
    				$model_audit->audit_uid = Yii::$app->user->identity->id;
    				$model_audit->audit_time = time();
    				$model_audit->trade_state = 0;//订单状态改为0
    				$model_audit->save();
    				
    				$msg = "您的订单（{$model_audit->trade_no}）已经改价成功，请认真核对后进入下一步骤。 ".' 退订回复TD';
    				$smser = new TextSmser();
    				//$smser->sendSMSbatch($model->userInfo['tel'], $msg);
    				$smser->sendSmsBatchNew($model->userInfo['tel'], $msg);
    				$model_log = new SmsLogRecord();
					$model_log->send_uid = Yii::$app->user->identity->id;
					$model_log->accept_uid = $model->user_id;
					$model_log->send_content = $msg;
					$model_log->send_time = time();
					$model_log->save();
					
    			}		
    			return $this->redirect(['view', 'id' => $model->id]);
    		} elseif(($model->price != $model->price_modify) && $model->audit_state==0) {//价格有修改和没有审核
    			return $this->render('audit', [//如何判断运费也被修改过？
    					'model' => $model,
    					]);

    	 }else{
    	     return $this->redirect(['index']);
    	 }
    }
    /**
     * Deletes an existing PayTrade model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the PayTrade model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return PayTrade the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = PayTrade::findOne($id)) !== null) {
        	$model = PayTrade::find()->where('pay_trade.id='.$id)->With(['userInfo'])->With(['adminInfo'])->With(['auditInfo'])->one();
        	$model->create_datetime = !empty($model->create_time) ? date('Y-m-d H:i:s',$model->create_time) : '-';
        	$model->modify_datetime = !empty($model->modify_time) ? date('Y-m-d H:i:s',$model->modify_time) : '-';
        	$model->audit_datetime = !empty($model->audit_time) ? date('Y-m-d H:i:s',$model->audit_time) : '-';
        	$model->username = $model->userInfo['username'];
        	$model->admin_username = !empty($model->admin_uid) ? $model->adminInfo['username'] : '-';//跟单客服
        	$model->audit_username = !empty($model->audit_uid) ? $model->auditInfo['username'] : '-';//审核人
        	$model->modify_admin_username =!empty($model->modify_uid) ? $model->modifyAdminInfo['username'] : '-';//改价员
			
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /*json组合拆分*/
    public function json_content($string_json){
    	$item_sales_service='';
    	$item_user_discount='';
    	$json = json_decode($model->content,true);
    	foreach ($json as $key => $value){
    		if($key == 'singleItem'){
    			foreach ($value as $vo){
    				$item_sales_service = $vo['info']['sales_service'];
    				$item_user_discount = $vo['info']['user_discount'];
    				foreach ($vo['items'] as $voo){
    					$item_id = $voo['item_id'];
    					$count = $voo['count'];
    					$mat = $voo['sku']['mat'];
    					$price_id = $voo['price_id'];
    					
    				}
    				
    			}
    		}
    	}	
    }
    public function actionPagePrintOrder($id){
    	$this->layout = 'main_small';
    	$model=$this->findModel($id);
    	$model->originPrice = PayTrade::calculate($model->content)['originPrice'];
    	$content=json_decode($model->content);
    	$pos=intval(strpos($model->content, "totle"));
    	if($pos>0){
    	    $totle=$content->totle;
    	    $sales_logistics=$totle[0]->info->sales_logistics;
    	    $sales_service=$totle[0]->info->sales_service;
    	    $sales_design=$totle[0]->info->sales_design;
    	    $model->price_freight=intval($sales_logistics);
    	    $model->installprice=intval($sales_service);
    	    $model->designprice=intval($sales_design);
    	    
    	}else{
    	    $model->price_freight=0;
    	    $model->installprice=0;
    	    $model->designprice=0;
    	}
    	
    	return $this->render('print_order', [
    	    'model' =>$model,
    			]);
    }
    
    
    /**退款相关*/
    public function actionRefund($id){
    	$model = PayTrade::find()->where("trade_state in(4,5)")->all();
    	return $this->render('refund', [
    			'model' => $model,
    			]);
    }
    
    /*
     * 改变订单的用户
     */
    public function actionChangeUser()
    {
        if (Yii::$app->request->isGet&&Yii::$app->request->get('id'))
        {
            $id=Yii::$app->request->get('id');
            $model=$this->findModel($id);
            return $this->renderAjax('_form_change_user',[
                'id'=>$id,
                'url'=>Yii::$app->request->get('url'),
                'model'=>$model
            ]);
        }
        elseif (Yii::$app->request->isPost&&Yii::$app->request->post('id'))
        {
            $model=$this->findModel(Yii::$app->request->post('id'));
            if ($model->load(Yii::$app->request->post())&&$model->changeUser()&&$model->save())
            {
                return $this->redirect(Yii::$app->request->post('url'));
            }
        }
    }
    /*
     * 审核线下转账支付
    */
    public function actionOfflinePay()
    {
    	
    	if (Yii::$app->request->isGet&&Yii::$app->request->get('id'))
    	{

    		$id=Yii::$app->request->get('id');
    		$model = LogPay::find()->joinWith('payTradeInfo')
    				->where("log_pay.type=5 AND pay_trade.id=".Yii::$app->request->get('id'))
    				->all();
    		
    		foreach ($model as $key => $val) {
    			$memo_xml = json_decode($val['memo_xml'],true);
    			$image_id = isset($memo_xml['imageid']) ? intval($memo_xml['imageid']) : 0;
    			
    			$model[$key]['transImage'] = Image::show_image($image_id);
    			$model[$key]['account'] = isset($memo_xml['account']) ? $memo_xml['account'] : '-';
    			$model[$key]['accountName'] = isset($memo_xml['accountName']) ? $memo_xml['accountName'] : '-';
    		}
    		return $this->renderAjax('_form_offline_pay',[
    				'id'=>$id,
    				'url'=>Yii::$app->request->get('url'),
    				'model'=>$model
    				]);
    	}
    	elseif (Yii::$app->request->isPost)
    	{
    		$params['return_code'] = 'SUCCESS';
    		$params['result_code'] = (bool)$_POST['audit_result']?'SUCCESS':'FAIL';
    		$params['return_msg'] = (bool)$_POST['reason']?$_POST['reason']:'线下支付审核成功';
    		$params['err_code'] = '';
    		$params['err_code_de'] = '';
    		$params['out_trade_no'] = $_POST['transaction_id'];
    		$params['admin_id'] = Yii::$app->user->identity->id;
    		$params['audit_time'] = time();
    		$payment = new offline();
    		$res = $payment->offline_pay($params);
    		if(!empty($res)){
    			echo json_encode(array('error'=>false,'msg'=>'提交成功'));
    		}else{
    			echo json_encode(array('error'=>true,'msg'=>'提交失败'));
    		}
    	}
    }
    /*
    public function actionOfflineAudit(){
    	if(Yii::$app->request->post()){
    		$params['return_code'] = 'SUCCESS';
    		$params['result_code'] = (bool)$_POST['audit_result']?'SUCCESS':'FAIL';
    		$params['return_msg'] = (bool)$_POST['reason']?'线下支付审核成功':'线下支付审核失败';
    		$params['err_code'] = '';
    		$params['err_code_de'] = '';
    		$params['out_trade_no'] = $_POST['transaction_id'];
    		$params['admin_id'] = Yii::$app->user->identity->id;
    		$params['audit_time'] = time();
    		$payment = new offline();
    		$res = $payment->offline_pay($params);
    		if(!empty($res)){
    			echo json_encode(array('error'=>false,'msg'=>'提交成功'));
    		}else{
    			echo json_encode(array('error'=>true,'msg'=>'提交失败'));
    		}
    	}
    	
    }*/
    /**
     * 运营商打印用户的订单
     */
    public function actionCustomOrderUpdate($trade_id){
    	$model_custom = CustomTrade::findOne(['trade_id'=>$trade_id]);
    	$model = $this->findModel($trade_id);
    	if($model_custom === null){
    		$model_custom = new CustomTrade();
    		$model_custom->trade_id = $trade_id;
    		$model_custom->content = $model->content;
    		$model_custom->save();
    	}		
    	if ($model_custom->load(Yii::$app->request->post()) && $model_custom->save()){
    		return $this->render('custom_order', [
    				'model' => $model_custom,
    				'payTradeModel' => $model,
    				]);
    	}
    	
    	return $this->render('custom_order', [
    			'model' => $model_custom,
    			'payTradeModel' => $model,
    			]);
    }
    
    public function actionPagePrintCustomOrder($trade_id){
    	$this->layout = 'main_small';
    	$model_custom = CustomTrade::findOne(['trade_id'=>$trade_id]);
    	
    	if($model_custom){
    		return $this->render('print_custom_order', [
    				'model' => $this->findModel($trade_id),//运营商的订单信息
    				'model_custom'=>$model_custom,//运营商客户的订单信息
    				]);
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have custom info'));
    	}
    }
    /**
     * 更新单品的成本价
     */
    public function actionSetCustomprice($trade_id,$all_price_list,$amount=0,$origin_amount=0){
    	$ask_cost_price=0;
    	$model = $this->findModel($trade_id);
    	$model_custom = CustomTrade::findOne(['trade_id'=>$trade_id]);
    	$_price_list = explode('@', $all_price_list);
    	
    	$_item_memo_arr=json_decode($model['content'],true);//转为数组
    	foreach ($_price_list as $key=>$val){
    		$_price_arr = explode('|', $val);$_custom_price = $_price_arr[0];$_item_id= $_price_arr[1];$_type= $_price_arr[2];
    		foreach ($_item_memo_arr[$_type] as $k=>$v){
    			foreach ($v['items'] as $kk=>$vv){
    				if($vv['item_id'] == $_item_id ){
    					$_item_memo_arr[$_type][$k]['items'][$kk]['custom_price'] = $_custom_price;
    					$count = $_item_memo_arr[$_type][$k]['items'][$kk]['count'];
    					$price_base = isset($_item_memo_arr[$_type][$k]['items'][$kk]['price_base'])?$_item_memo_arr[$_type][$k]['items'][$kk]['price_base']:0;
    					$price_discount = isset($_item_memo_arr[$_type][$k]['items'][$kk]['price_discount'])?$_item_memo_arr[$_type][$k]['items'][$kk]['price_discount']:1;
    						
    					$_price_custom = isset($_item_memo_arr[$_type][$k]['items'][$kk]['_price_custom'])?$_item_memo_arr[$_type][$k]['items'][$kk]['_price_custom']:0;
    					$_price_discount = isset($_item_memo_arr[$_type][$k]['items'][$kk]['_price_discount'])?$_item_memo_arr[$_type][$k]['items'][$kk]['_price_discount']:1;
    					    					
    					$custom_amount = $_custom_price * $count;//客户金额
    					$custom_origin_amount = ($price_base * $price_discount + $_price_custom * $_price_discount) * $count;
    					$origin_amount += $custom_origin_amount;
    					$amount += $custom_amount;
    				}
    			}

    		}
    	}
    	$_item_memo_arr['origin_amount'] = $origin_amount;
    	$_item_memo_arr['amount'] = $amount;
    	$_item_memo = json_encode($_item_memo_arr);//重新组合的json字符串
    	$model_custom->content = $_item_memo;
    	$model_custom->save();
    	echo json_encode(array('error'=>false,'msg'=>'折扣价更新成功'));
    } 
    
    /*财务报表*/
    public function actionFinanceSale()
    {
    	if(Yii::$app->user->can('finance-sale')){
	    	$searchModel = new PayTradeSearch();
	    	$return = $searchModel->reportSearch(Yii::$app->request->queryParams);   	
	    	//运营的信息
	    	$user_model = UserInfo::get_yys_user();
	    	return $this->render('finance_report', [
	    			'searchModel' => $searchModel,
	    			'dataProvider' => $return['dataProvider'],
	    			'info'		=>$return['amount'],
	    			'user_model'  => $user_model,
	    			]);
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    /**
     * 众筹财务报表
     */
    public function actionCrowdFinanceSale(){
        if(Yii::$app->user->can('crowd-financesale')){
            $searchModel = new PayTradeSearch();
            $return = $searchModel->crowdreportSearch(Yii::$app->request->queryParams);
            //运营商城市下拉选择
             $user_model = UserInfo::get_yys_user();
             //  $user_model = UserInfo::get_type_user("5");
            return $this->render('crowd-finance_report', [
                'searchModel' => $searchModel,
                'dataProvider' => $return['dataProvider'],
                'info'		=>$return['amount'],
                'user_model'  => $user_model,
            ]);
        }else{
            throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
        }
    }
	/**
	 * 设计师订单
	 */
	public function actionDesigner(){
		$searchModel = new PayTradeSearch();
		$tradeList = PayTrade::find()->where("pay_trade.price_state=1 or pay_trade.price_state=11 and pay_trade.content like '%coupon%' ")
		->all();
    	$dataProvider = $searchModel->searchDesigner(Yii::$app->request->queryParams);
    	  return $this->render('designer_index', [
    			'searchModel' => $searchModel,
    			'dataProvider' => $dataProvider,
    	  		'tradeList'=>$tradeList
    	]);  
	}
	
	/**
	 * 打印设计师报表
	 */
	public function actionPrintdesigner($year,$type=3){
		$payTrade=new PayTrade();
		if($year==""){
			$year=date("y");
		}
		//根据年份查询  id 用户名  购买用户 电话 所属地区   用户级别  不同季度的金额 合计
		$user_type = Yii::$app->user->identity->user_type;
    	//如果是非管理员，则根据地址过滤
		$param=array();
    	$sql=" SELECT  pay_trade.user_id,pay_trade.create_time,sys_user_designer.name nickname,
				user_info.`username`,user_info.`tel`,sys_user_designer.address  user_area,user_info.user_type_class
				FROM pay_trade ,user_info,sys_user_designer
				WHERE pay_trade.trade_class=1 and pay_trade.user_id=user_info.id 
				AND pay_trade.`user_id`=sys_user_designer.`uid` 
				AND pay_trade.`price_state`  IN (1,11) 
				and pay_trade.content like '%coupon%'
    			AND user_info.`user_type`=$type
				";
    	if ($user_type != 1 ){//非后台管理员
    		if(\Yii::$app->user->can('yys_sale_view')){
    			$address=SysUserDesigner::findOne(['uid'=>Yii::$app->session['user_id']])->address;
    			$sql.=" and sys_user_designer.address like '%:address%' ";
    			$param=array(":address"=>$address);
    		} 
    	} 
    	$sql.=" GROUP BY pay_trade.`user_id` order by pay_trade.user_id desc ";
    	$designerList=PayTrade::findBySql($sql,$param)->all();
    	foreach($designerList as &$trade){
    		$userid=$trade->user_id;
    		//1.自己的四个季度订单金额      2.查询他的子订单金额   累加金额 
    		$quarty1_money=$payTrade->getSumPriceByUserid($year,$userid,1);
    		$quarty2_money =$payTrade->getSumPriceByUserid($year,$userid,2);
    		$quarty3_money =$payTrade->getSumPriceByUserid($year,$userid,3);
    		$quarty4_money =$payTrade->getSumPriceByUserid($year,$userid,4);
    		$quarty0_money=$payTrade->getSumPriceByUserid($year,$userid,0);
    		$trade['quarter_one']=$quarty1_money;
    		$trade['quarter_two']=$quarty2_money;
    		$trade['quarter_three']=$quarty3_money;
    		$trade['quarter_four']=$quarty4_money;
    		$trade['amount']=$quarty0_money;
    	}
    	if($type==3){
    		$name="设计师";
    	}else{
    		$name="装饰公司";
    	}
    	$html="<div><h3  style='margin-left:450px;'>".$year."年".$name."报表</h3>";
    	
    	$html.="<h5>共".count($designerList)."条数据. </h5>";
    	$html.="<h5>".date("Y-m-d H:i:s",time())."</h5>";
    	$html.='<table  border="1"  bordercolor="#000000" cellspacing="0px" style="margin-top:30px;font-size:11px;">';
						
    	$html.='<tr style="height:25px;text-align:center;" ><td style="width:80px;">ID</td><td style="width:100px;">用户名</td><td style="width:110px;">购买用户</td>
    			<td style="width:110px;">电话</td><td style="width:200px;">所属地区</td><td style="width:50px;">级别</td>
    			<td style="width:100px;">第一季度	</td><td style="width:100px;">第二季度	</td><td style="width:100px;">第三季度</td>
    			<td style="width:100px;">第四季度</td><td style="width:100px;">合计</td></tr>';
    	foreach($designerList as $desiger){
    		$html.='<tr style="height:25px;">';
    		$html.='<td style="text-align:left;">'.$desiger->user_id.'</td>';
    		$html.='<td style="text-align:left;">'.$desiger->nickname.'</td>';
    		$html.='<td style="text-align:left;">'.$desiger->username.'</td>';
    		$html.='<td style="text-align:left;">'.$desiger->tel.'</td>';
    		$html.='<td style="text-align:left;">'.$desiger->user_area.'</td>';
    		$html.='<td style="text-align:left;">'.$desiger->user_type_class.'</td>';
    		$html.='<td style="text-align:right;">'.number_format($desiger->quarter_one).'</td>';
    		$html.='<td style="text-align:right;">'.number_format($desiger->quarter_two).'</td>';
    		$html.='<td style="text-align:right;">'.number_format($desiger->quarter_three).'</td>';
    		$html.='<td style="text-align:right;">'.number_format($desiger->quarter_four).'</td>';
    		$html.='<td style="text-align:right;">'.number_format($desiger->amount).'</td>';
    		$html.='</tr>';
    	}
    	$html.='</table></div>';
    	echo $html;exit();
	}
	
	/**
	 * 装饰公司订单
	 */
	public function actionComany(){
		$searchModel = new PayTradeSearch();
    	$dataProvider = $searchModel->searchComany(Yii::$app->request->queryParams);
    	  return $this->render('company_index', [
    			'searchModel' => $searchModel,
    			'dataProvider' => $dataProvider,
    	]); 
	}
	/**
	 * 某设计师或者某装饰公司的订单列表  包括使用了她优惠券的用户订单
	 */
	public function actionDesigner_view($user_id,$quarter,$year){
		$payTrade=new PayTradeSearch();
	 //swith结束
		//根据季度筛选时间
		//test
		$userInfo=SysUserDesigner::findOne($user_id);
		$searchModel = new PayTradeSearch();
		$dataProvider = $searchModel->searchDesignerView($user_id,$quarter,$year,Yii::$app->request->queryParams);
		return $this->render('designer_view', [
				'searchModel' => $searchModel,
				'dataProvider' => $dataProvider,
				'name'=>$userInfo['name']."第".$quarter."季度"
		]);
	}
}
